//
//  KSTempListVC.swift
//  ZYA
//
//  Created by 邱仙凯 on 2022/7/11.
//  Copyright © 2025 aowang. All rights reserved.
//


import UIKit

class KSTempListVC: UIViewController {
    var rootTemp = MainTempModel(JSON:["":""])!
    
     lazy var searchItem:UIBarButtonItem = {
        let searchItem = UIBarButtonItem(image: UIImage(named: "guolv"), style: .done, target: self, action: #selector(tempSearchAction))
        return searchItem
    }()
     lazy var searchItem_ch:UIBarButtonItem = {
        
        
        let v = UIButton.creat4Item(title: "筛选") { _ in
            self.tempSearchAction()
        }
        let barv = UIBarButtonItem(customView:v)
        return barv
 
    }()
     lazy var addItem:UIBarButtonItem = {
        let addItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addClick))
        addItem.tintColor = .black
        return addItem
    }()
     lazy var addItem_ch:UIBarButtonItem = {
        let v = UIButton.creat4Item(title: "新增") { _ in
            self.addClick()
        }
        let barv = UIBarButtonItem(customView:v)
        return barv
    }()
   
  
    
     lazy var scanItem:UIBarButtonItem = {
        let v = UIBarButtonItem(image: UIImage(named: "saoma"), style: .done, target: self, action: #selector(scanAction))
        return v
    }()
    var bannerH:CGFloat = 46
    
     lazy var filterBanner:ComSearch2V = {
        let v = ComSearch2V(frame: CGRect(x:0,y:0,width: KSGlobal.screenW,height: bannerH))
         v.setBannerData(arr: [])
        return v
    }()
    
  
    lazy var tableView: UITableView = {
        let v = UITableView()
        v.delegate = self
        v.dataSource = self
        return v
    }()
    fileprivate var segmenteControl: UISegmentedControl!
    var templateHandle = [TemplateModel]()
    var templateDic = [[String:Any]]()
    // 分组列表
    var sortDataArray = [([String:Any],[[String:Any]])]()
    // 单纯列表
    var dataArray = [[String:Any]]()


    

    fileprivate var audit_mark = ""
 
    var templateFilter = [TemplateModel]()
    fileprivate var templateM = [TemplateModel]()
    // 告诉seg 刷一下 item
    var configRightClo:(()->())?
 
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if !OfflineFileBoard.isUseFileClipPlatform() {
            // 不使用切片的项目保留原逻辑
            OfflineFileBoard.shared.checkOfflineFile()
        }
    }
    
 
 
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 打开重传的数据库, 没有使用切片的会在这里开打数据库,启动切片的会启动就打开数据库
        if !OfflineFileBoard.isUseFileClipPlatform() {
            ClipOfflineTool.shared.openDB()
        } else {
            ClipOfflineTool.shared.checkOfflineFile()
        }
        
        view.backgroundColor = #colorLiteral(red: 0.9607843137, green: 0.9607843137, blue: 0.9607843137, alpha: 1)
        self.title = rootTemp.menu_nm
        if #available(iOS 15.0, *) {
                    tableView.sectionHeaderTopPadding = 0
                }
        tableView.register(KSTempHeader.self, forHeaderFooterViewReuseIdentifier: KSTempHeader.identifier)
        tableView.tableFooterView = UIView()
        view.addSubview(tableView)
        var tableTopMargin:CGFloat = 0
        if TempAppear.shared.newFilterStyle {
            tableTopMargin = bannerH
         }
        remakeTableView(topM: tableTopMargin)
        listFecthTemp()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            PermissionsHelper.cameraEnable()
        }
        checkDevice()
    }
    
    func remakeTableView(topM:CGFloat) {
        
        tableView.snp.remakeConstraints { make in
            make.top.equalToSuperview().offset(topM)
            make.right.left.bottom.equalToSuperview()
        }
    }

    
    func checkDevice() {
        
        
        if DeveloperTool.shared.GetAllowAllLimit() {
 
        
       } else {
 
           if rootTemp.setCheckDevice {
               TempHelper.shared.temp_checkDevice(vc: self)
               
           }
       }
        
       
    }
    
    
    func listFecthTemp() {
        fetchTempData(menuid: rootTemp.id_key.unwrap) { infos, infoDicArr in
            self.templateHandle = infos
            self.templateDic = infoDicArr
            self.templateFilter = infos.filter{ $0.placeFlag == "3" }
            self.setup()
        }
    }
    
    


    func setup() {
        
        templateM = templateHandle.filter { $0.placeFlag == "1" && $0.isSHowList == "1" }
        if templateM.count > 30 {
            KSToast("列表显示超过30个的暂不显示，目前\(templateM.count)个，\n建议配置关闭多余的列表显示字段，仅显示重要字段",duration: 2)
            templateM = Array(templateM[0..<30])
        }
        if templateM.count == 0 {
            KSToast("请配置列表显示字段",duration: 2)
        }
        
        configFilter()
        
      
        
        self.tableView.backgroundColor = Theme.awModuleBgColor
        self.tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(GlobalTableViewCell.self, forCellReuseIdentifier: GlobalTableViewCell.identifier)
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
        
        
        tableView.mj_header = KSRefreshHeader { [unowned self] in
            self.filterBanner.filterV!.page = self.filterBanner.filterV!.default_page
            self.filterBanner.filterV!.filterDic.updateValue("\(self.filterBanner.filterV!.page)", forKey: "page")
            self.network()
        }
      
        if rootTemp.listGroup.count < 1 {
            tableView.mj_footer = KSRefreshFooter { [unowned self] in
                self.filterBanner.filterV!.page += 1
                self.filterBanner.filterV!.filterDic.updateValue("\(self.filterBanner.filterV!.page)", forKey: "page")
                self.network()
            }
        }
        
        
        tableView.mj_header?.beginRefreshing()
        
    }
    

    
    
    
    
    @objc func scanAction() {
        SwiftScanHelper.shared.openScan(controller:self) { rst in
            self.addAction(rst)
        }
    }

    func network() {
        // 处理拼接在路径后的硬参数
        var realUrl = rootTemp.query_url.unwrap
        var sufDic = [String:String]()
        if rootTemp.query_url.unwrap.contains("?") {
            realUrl = rootTemp.query_url.unwrap.preChar(char: "?").unwrap
            let sufArr = rootTemp.query_url.unwrap.sufChar(char: "?").unwrap.components(separatedBy: "&")
            for item in sufArr {
                sufDic.updateValue(item.sufChar(char: "=").unwrap, forKey: item.preChar(char: "=").unwrap)
            }
        }
        let realDic = deepMerge(filterBanner.filterV!.filterDic, sufDic)
        
        KSNetwork.shared.doRequest(API.temp(.path(path: realUrl, paramDic: realDic)),showHud: false) {  [weak self] (data:BaseResult<OperateResult>) in
            guard let `self` = self else {return}
            if data.flag == TRUE {
                if self.filterBanner.filterV!.page == self.filterBanner.filterV!.default_page {
                    self.dataArray.removeAll()
                }
                self.dataArray += data.infoDicArr
                self.dealData()
                self.tableView.reloadData()
                self.tableView.mj_header?.endRefreshing()
                self.tableView.mj_footer?.endRefreshing()
                if data.infoDicArr.count < self.filterBanner.filterV!.default_size {
                    self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
        
        
    }

    func dealData() {
  
        if rootTemp.listGroup.count > 0  {
            
          
 
  
            let sss = generateTwo(self.dataArray) { aa,bb in
                let straa = getDolVal(rootTemp.listGroup[0],main: aa,rootTemp: rootTemp).0
                let strbb = getDolVal(rootTemp.listGroup[0],main: bb,rootTemp: rootTemp).0
                return straa == strbb
            }
            self.sortDataArray.removeAll()
            for i in 0..<sss.count {
                
                // 列表展示文字
            let str = getSortGroupVal(rootTemp.listGroup[1],dicArr: sss[i])
                    
                if i == 0 {
                    let one = ([TKey.openx:"true",TKey.groupShow:str],sss[i])
                    self.sortDataArray.append(one)
                } else {
                    let one = ([TKey.openx:"false",TKey.groupShow:str],sss[i])
                    self.sortDataArray.append(one)
                 }
            }
            
            
        }
    }
    
    // scanResult扫码结果代入新增
    @objc func addClick() {
        self.addAction()
    }
    

    
}


extension KSTempListVC:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.sortDataArray.count > 0 {
            return self.sortDataArray.count
        } else {
            return 1
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.sortDataArray.count > 0 {
            let openx = any2Str(self.sortDataArray[section].0[TKey.openx])
            return openx == TRUE ? self.sortDataArray[section].1.count : 0
        } else {
            return self.dataArray.count
        }
     
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: GlobalTableViewCell.identifier, for: indexPath) as!
        GlobalTableViewCell
        var one = [String:Any]()
        if self.sortDataArray.count > 0 {
            one = self.sortDataArray[indexPath.section].1[indexPath.row]
        } else {
            one = dataArray[indexPath.row]
        }
        
      
        
        var contArr = [(String,String?,String)]()
        var btnTitleArr:[String] = []
        var titleAndStatus:(String,String)!
        
        let str = getDolVal(rootTemp.left_title.unwrap,main: one,rootTemp: rootTemp).0
        let str2 = getDolVal(rootTemp.right_title.unwrap,main: one,rootTemp: rootTemp).0
        titleAndStatus = (str,str2)
        if appendLiucheng(one:one) {
            btnTitleArr += ["流程图"]
        }
        if appendTijiao(one:one) {
            btnTitleArr += ["提交"]
        }
        if appendFanTijiao(one:one) {
            btnTitleArr += ["反提交"]
        }
        if appendDelete(one:one) {
            btnTitleArr += ["删除"]
        }
        if appendModify(one:one) {
            btnTitleArr += ["修改"]
        }
        
        
        
        
        // 自定义按钮
        for item in self.rootTemp.defiBtnArr {
            if item.count > 0 {
                let bNm = item[0]
                if fixedBtnControl(one:one,oriBtnName: bNm) == .agree {
                    btnTitleArr.append(bNm)
                } else if fixedBtnControl(one:one,oriBtnName: bNm) == .disAgree {
                    
                } else {
                    btnTitleArr.append(bNm)
                }
                
            } else {
                KSToast("自定义按钮配置错误")
            }
        }
        
        
        
        for i in 0..<self.templateM.count {
            let name = any2Str(self.templateM[i].field_annotation.unwrap)
            let conditionColor = self.templateM[i].conditionColor
            //条件颜色： 默认无，由系统自动配置颜色
            var colorS = ""
            for item in conditionColor {
                let boolFlag =  expressionReplace(item.0,main:one,rootTemp: rootTemp)
                if boolFlag {
                    colorS = item.1
                }
            }
            
             let value = any2Str(one[self.templateM[i].field_nm.unwrap])
            contArr.append((name,value,colorS))
            
        }
         
            cell.setDataSource(contentArr: contArr,btnTitleArr: btnTitleArr,titleAndStatus: titleAndStatus)
 
        cell.btnGroupclickAction = {[indexPath,one] tag,titlex in
            
            if titlex == "流程图" {
                // 流程图
                TempHelper.shared.viewFlowPic(controller: self, process: "", voc_cd: self.rootTemp.flow_voucd.unwrap, vou_id: any2Str(one["id_key"]))
            } else if titlex == "提交" {
                if self.judgeEditEnable(one:one) {
                    self.go2Tijiao(one: one)
                }
            } else if titlex == "反提交" {
                if self.judgeEditEnable(one:one) {
                    self.go2Fantijiao(one: one)
                }
            } else if titlex == "删除" {
                if self.judgeEditEnable(one:one) {
                    self.go2Delete(one:one)
                }
            }else if titlex == "修改" {
                if self.judgeEditEnable(one:one) {
                    self.go2ModifyForm(indexPath.row)
                }
            } else {
                // 自定义按钮事件
                if let indexxx = self.rootTemp.defiBtnArr.getIndexFor({ onex in
                    return titlex == onex[0]
                }) {
                    let oneXX = self.rootTemp.defiBtnArr[indexxx]
                 
                    guard oneXX.count > 3 else {
                        let joinONexx = oneXX.joined(separator: ":")
                        alertUtil(title: "自定义按钮配置错误",message: "当前：\n\(joinONexx) \n正确示例 ：\n 生成报废单:z_one_no=${z_one_no}&z_zzda_id=${z_zzda_id}:0:form:精液报废记录\n", operateS: [nameAction(name: "确定", action: { _ in
                            
                        })])
                        return
                    }
                    
                  
                    
                    
                    switch oneXX[3] {
                    case ZiDingType.yunmou.rawValue:
                        let arr = getDolVal(oneXX[1],main: one,rootTemp: self.rootTemp).1
                        
                        guard arr.count == 12 else {
                            KSToast("未识别yunmou语法")
                            return
                        }
                        
                        go2YummouVideo(id_key_new:any2Str(one["id_key_new"]),id_key:any2Str(one["id_key"]),title:arr[1],token: arr[3],Device: arr[5], Channel: arr[7], start: arr[9], end: arr[11],controller: self) {
                            self.tableView.mj_header?.beginRefreshing()
                        }
                        
                        
                        
                    case ZiDingType.api.rawValue,ZiDingType.web.rawValue:
                        let reU = getUrl4ziding(str: oneXX[1], mainDic: one)
                        
                        if oneXX[2] == "1" {
                            alertUtil(self, title: "确认\(titlex)", operateS: [nameAction(name: "确定", action: { (_) in
                                
                                if oneXX[3] == ZiDingType.api.rawValue {
                                    
                                    self.performApi(url: oneXX[1],one:one, titlex: oneXX[0])
                                    
                                } else {
                                    self.go2web(url:reU, title: oneXX[0])
                                }
                                
                            })])
                        } else {
                            if oneXX[3] == ZiDingType.api.rawValue {
                                self.performApi(url: oneXX[1],one:one, titlex: oneXX[0])
                            } else {
                                self.go2web(url:reU, title: oneXX[0])
                            }
                        }
                    case ZiDingType.lov.rawValue:
                        // 自定义按钮的lov展示型
                        
                        let fiArr = self.templateHandle.filter { $0.field_nm == oneXX[1] }
                        if fiArr.count > 0 {
                            let oneT = fiArr.first!
                            var pathDic = url2PathDic(mainDic: one,currDetaiDic: nil,arr: oneT.pathHandler.comPa)
                            
                            // 单选
                            let keyPa = oneT.pathHandler.spePa.filter{ $0.contains("keyword") }
                            let showSearch:Bool = (keyPa.count > 0)
                            let sizePa = oneT.pathHandler.spePa.filter{ $0.contains("size") }
                            let vc = KSSingleSelectNetUtil(searchType:showSearch ? .barAndScan : .none)
                            vc.title = oneXX[0]
                            
                            if sizePa.count > 0,intTran(sizePa.first!.sufChar(char: "=")) > 0 {
                                vc.size = intTran(sizePa.first!.sufChar(char: "="))
                            } else {
                                vc.size = 0 // 0为不分页
                            }
                            vc.kSSingleSelectNetNetwork = { page,size,keyword in
                                if showSearch {
                                    for ii in 0..<keyPa.count {
                                        pathDic.updateValue(keyword, forKey: keyPa[ii].preChar(char: "=").unwrap)
                                    }
                                }
                                if size != 0 {
                                    pathDic.updateValue("\(page)", forKey: "page")
                                    pathDic.updateValue("\(size)", forKey: "size")
                                }
                                KSNetwork.shared.doRequest(API.temp(.path(path: oneT.pathHandler.path, paramDic: pathDic))) { (data:BaseResult<OperateResult>) in
                                    if data.flag == TRUE {
                                        if page == 1 {
                                            vc.allArr.removeAll()
                                        }
                                        vc.showData(arr:data.infoDicArr)
                                        
                                    } else {
                                        KSToast(data.errorCombine.unwrap)
                                    }
                                }
                            }
                            vc.kSSingleSelectNetShowCell = { cell,model in
                                
                                var contArr = [(String,String?)]()
                                
                                
                                
                                for item in oneT.lovShowArr {
                                    let pre = item.preChar(char: ":").unwrap
                                    let suf = item.sufChar(char: ":").unwrap
                                    contArr.append((suf,any2Str((model as! [String:Any])[pre])))
                                }
                                
                                cell.setDataSource(contentArr: contArr)
                                
                                
                            }
                            vc.backClosure = { _ in
                                // 仅显示
                                
                            }
                            
                            self.navigationController?.pushViewController(vc,animated:true)
                            
                        } else {
                            KSToast("未配置lov型")
                        }
                        
                    case ZiDingType.form.rawValue:
                       
                        
                        go2SpeMenuForm(oneXX:oneXX,one: one,straightDic: [:],vc:self)
                        
                    case ZiDingType.flow.rawValue:
                  
                        go2Flow(oneXX:oneXX, chooseUser: [],one:one,vc:self)
                      
                    case ZiDingType.uniapp.rawValue:
                        let reU = getUrl4zidingUniapp(str: oneXX[1], mainDic: one)
                        
                        if oneXX[2] == "1" {
                            alertUtil(self, title: "确认\(titlex)", operateS: [nameAction(name: "确定", action: { (_) in
                                
                                ConfigFormUniapp.openPage(path: reU)
                                
                            })])
                        } else {
                            ConfigFormUniapp.openPage(path: reU)
                        }
                            
                        
                    default:
                        KSToast("未识别自定义按钮类型")
                    }
                    
                    
                }
            }
            
            
            
            
        }
        
        
        
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
        guard !rootTemp.setViewForbidden else {
             return
        }
        
        
        var one = [String:Any]()
        if self.sortDataArray.count > 0 {
            one = self.sortDataArray[indexPath.section].1[indexPath.row]
        } else {
            one = dataArray[indexPath.row]
        }
        
        
        if  self.rootTemp.webFormUrl != "" {
            let cwebV = SepWebVC()
            
            let uurl =  getUrl4ziding(str: self.rootTemp.webFormUrl, mainDic: one)
            cwebV.reportUrl = uurl
            KSLog(uurl)
            cwebV.excuteType = .view
             cwebV.title = self.rootTemp.menu_nm
            self.navigationController?.pushViewController(cwebV, animated: true)
            
        } else {
            if self.rootTemp.query_form_url.unwrap != "" {
                let view  = ConfigMenuForm(rootTemp: self.rootTemp, templateHandle: self.templateHandle, templateDic: self.templateDic)
                view.excuteType = .view
                view.main = one
                view.refreshClosure = {
                    self.tableView.mj_header?.beginRefreshing()
                }
                self.navigationController?.pushViewController(view, animated: true)
            }
        }
        
        
     
        
        
        
    }
    // 活跃细表 只开一个细表，当前活跃的细表
    func activeListRow(indexx:Int,status:String) {
        if status == TRUE {
            // 把目前开的关了
            for i in 0..<self.sortDataArray.count {
                if any2Str(self.sortDataArray[i].0[TKey.openx]) == TRUE {
                    self.sortDataArray[i].0[TKey.openx] = "false"
                    let set = IndexSet(integer:i)
                    self.tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
                }
                
            }
       
        }
        self.sortDataArray[indexx].0[TKey.openx] = status
        let set = IndexSet(integer:indexx)
        self.tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
        
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: KSTempHeader.identifier) as? KSTempHeader else {
            fatalError()
        }
        let tap = UITapGestureRecognizer()
        tap.numberOfTapsRequired = 1
        tap.addTap { [unowned self] _ in
            if any2Str(self.sortDataArray[section].0[TKey.openx]) == TRUE {
                self.activeListRow(indexx: section,status:"false")
            } else {
                self.activeListRow(indexx: section,status:"true")
            }
           
        }

        headerView.lab1.text = any2Str(self.sortDataArray[section].0[TKey.groupShow]) 
        
        headerView.addGestureRecognizer(tap)
        if  self.sortDataArray.count > section ,
            any2Str(self.sortDataArray[section].0[TKey.openx]) == TRUE {
            headerView.rightImg.setBackgroundImage(UIImage(named: "zk_1"), for: .normal)
        } else {
            headerView.rightImg.setBackgroundImage(UIImage(named: "zk_2"), for: .normal)
        }
        return headerView
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if self.sortDataArray.count > 0 {
            return 60
        } else {
            return 0
        }
    }
    
}




